<template>
  <div class="policeCriminalInvestigationList" :style="[{'zoom': zoom}]">
    <div class="list-search">
      <div class="singe-search">
        <el-input v-model="pageForm['receiver']" placeholder="请输入接收人姓名" clearable></el-input>
      </div>
      <div class="singe-search">
        <el-input v-model="pageForm.receiverPhone" placeholder="请输入手机号" clearable></el-input>
      </div>
      <div class="singe-search">
        <el-radio-group v-model="pageForm.searchType">
          <el-radio :label="1">3天内</el-radio>
          <el-radio :label="2">1月内</el-radio>
          <el-radio :label="3">指定日期：</el-radio>
        </el-radio-group>
      </div>
      <div class="singe-search">
        <el-date-picker ref="daterange" v-model="daterange" type="daterange" range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
        </el-date-picker>
      </div>
      <div class="singe-search">
        <el-button class="singe-search-btn1" @click="queryList">查询</el-button>
        <el-button class="singe-search-btn2" @click="resetForm">重置</el-button>
        <el-button class="singe-search-btn1" @click="addPoliceCriminalInvestigation">新增</el-button>
      </div>
    </div>
    <div class="table-main">
      <el-table :data="tableData" style="width: 100%" :height="tableHeight">
        <el-table-column type="index" label="序号" width="70" align="center">
        </el-table-column>
        <el-table-column prop="receiver" label="接收人" min-width="80">
        </el-table-column>
        <el-table-column prop="receiverPhone" label="手机号" min-width="110">
        </el-table-column>
        <el-table-column prop="smsList" label="短信发送" width="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.smsList.length === 0" style="color: #EB5757;">未发送</span>
            <div v-else @click="handleOpenSmsSendingSituationDialog(scope.row)"
                 style="width: 66px;height: 26px;margin-left: 9px; background: rgba(85,144,200,0.05);border-radius: 2px 2px 2px 2px;
                 opacity: 1;border: 1px solid rgba(54,121,222,0.55); text-align: center; cursor: pointer;">
              {{ scope.row.smsList.length }}条
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="smsLastSendTime" label="最新发送时间" min-width="150">
        </el-table-column>
        <el-table-column prop="field7" label="位置信息" min-width="100">
          <template slot-scope="scope">
            <img style="width: 63px; height: 34px; cursor: pointer;" v-if="scope.row.feedBackList.length > 0"
                 src="../../img/images/policeInformation/ic_ditu.png"
                 @click="handleOpenPoliceCriminalInvestigationMapDialog(scope.row)"/>
          </template>
        </el-table-column>
        <!--        <el-table-column prop="status" label="通知出警" min-width="90" align="center">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span v-if="scope.row.status === 1">是</span>-->
        <!--            <span style="color: #EB5757" v-else>否</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" width="300" align="center" :resizable="false">
          <template slot-scope="scope" v-if="scope.row.status === 0">
            <el-button type="text" @click="handlerSendSms(scope.row)" v-if="scope.row.smsList.length === 0"
                       :disabled="scope.row.status === 1"
                       style="color:#EB5757;margin-left: 15px; margin-right: 15px;font-size:14px">发送短信
            </el-button>
            <el-button type="text" @click="handlerSendSms(scope.row)" v-else
                       :disabled="scope.row.status === 1"
                       style="color:#2E488B;margin-left: 15px; margin-right: 15px;font-size:14px">重发短信
            </el-button>
<!--            <span style="color:#C1D3EE;">|</span>-->
<!--            <el-button type="text" @click="handleOpenPoliceCriminalInvestigationMapDialog(scope.row)"-->
<!--                       style="color:#2E488B;margin-left: 15px; margin-right: 15px;font-size:14px">出警-->
<!--            </el-button>-->
            <span style="color:#C1D3EE;" v-if="scope.row.smsList.length === 0">|</span>
            <el-button type="text" @click="handlerEdit(scope.row)"
                       v-if="scope.row.smsList.length === 0"
                       style="color:#2E488B;margin-left: 15px; margin-right: 15px;font-size:14px">编辑
            </el-button>
            <span style="color:#C1D3EE;" v-if="scope.row.smsList.length === 0">|</span>
            <el-button type="text" v-if="scope.row.smsList.length === 0"
                       @click="handlerDelete(scope.row)"
                       style="color: #2E488B;margin-left: 15px;font-size:14px">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="pageForm.current" :page-sizes="[10, 20, 50, 100]" :page-size="pageForm.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="pageForm.total">
      </el-pagination>
    </div>
    <el-dialog :title="title" :visible.sync="addPoliceCriminalInvestigationDialogVisible" width="728px"
               :before-close="handleCloseAddPoliceCriminalInvestigationDialog" append-to-body destroy-on-close
               :close-on-click-modal="false" custom-class="addDialog" top="50px">
      <el-form :model="addForm" :rules="rules" ref="addForm" label-position="top" label-width="100px">
        <el-form-item label="接收人：" prop="receiver">
          <el-input v-model="addForm.receiver" placeholder="请输入接收人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="receiverPhone">
          <el-input v-model="addForm.receiverPhone" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
					<el-button @click="handleCloseAddPoliceCriminalInvestigationDialog" size="small">
						取 消
					</el-button>
					<el-button type="primary" @click="submitDialog" size="small" style="backgroud-color:#2E488B">
						提 交
					</el-button>
				</span>
    </el-dialog>
    <el-dialog title="短信发送情况" :visible.sync="smsSendingSituationDialogVisible" width="728px"
               :before-close="handleCloseSmsSendingSituationDialog" append-to-body destroy-on-close
               :close-on-click-modal="false"
               custom-class="smsSendingSituationDialog">
      <el-table :data="smsList" style="width: 100%; margin-bottom: 30px;" height="280" border>
        <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
        <el-table-column min-width="120" label="接收人" :show-overflow-tooltip="true" prop="sender">
        </el-table-column>
        <el-table-column min-width="120" label="手机号" :show-overflow-tooltip="true" prop="receiverPhone">
        </el-table-column>
        <el-table-column min-width="120" label="发送时间" :show-overflow-tooltip="true" prop="createTime">
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="刑侦地图" :visible.sync="policeCriminalInvestigationMapDialogVisible" width="1160px" top="100px"
               :before-close="handleClosePoliceCriminalInvestigationMapDialog" append-to-body destroy-on-close
               :close-on-click-modal="false" custom-class="policeCriminalInvestigationMapDialog">
      <el-table ref="singleTable" :data="tableData2" style="width: 100%; margin-bottom: 24px;" height="150" border
                highlight-current-row
                @current-change="handleTable2CurrentChange">
        <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
        <el-table-column min-width="70" label="接收人" :show-overflow-tooltip="true" prop="receiver">
        </el-table-column>
        <el-table-column min-width="90" label="手机号" :show-overflow-tooltip="true" prop="receiverPhone">
        </el-table-column>
        <el-table-column min-width="120" label="地址反馈时间" :show-overflow-tooltip="true" prop="feedbackTime">
        </el-table-column>
        <el-table-column min-width="120" label="地图地址" :show-overflow-tooltip="true" prop="mapAddress">
        </el-table-column>
        <el-table-column min-width="140" label="经纬度信息" :show-overflow-tooltip="true" prop="coordinates">
        </el-table-column>
      </el-table>
      <div class="map" id="map">
      </div>
      <span slot="footer" class="dialog-footer">
				<el-button @click="handleClosePoliceCriminalInvestigationMapDialog" v-if="isShowPoliceBut">取消</el-button>
				<el-button type="primary" @click="submitMap" v-if="isShowPoliceBut">复制刑侦信息</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>

import {
  getList,
  getDetails,
  submit,
  deleteCriminalInvestigation
} from "@/api/policeCriminalInvestigation/list";
import {sendSms} from "@/api/sms";
import {copyText} from '@/util/util';
import AMapLoader from '@amap/amap-jsapi-loader';
import {sendMsg} from "@/api/policeInformation/list";

const validatePhone = (rule, value, callback) => {
  if (!(/^1[3456789]\d{9}$/.test(value))) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};
export default {
  name: 'PoliceCriminalInvestigationList',
  data() {
    return {
      width: 1848,
      zoom: 1,
      daterange: [],
      pageForm: {
        current: 1,
        size: 10,
        total: 0,
        receiver: '',
        receiverPhone: '',
        searchType: 3
      },
      tableData: [],
      addForm: {},
      rules: {
        receiver: [{
          required: true,
          message: '请填写接收人',
          trigger: 'blur'
        }],
        receiverPhone: [{
          required: true,
          message: '请填写手机号',
          trigger: 'blur'
        }, {validator: validatePhone, trigger: 'blur'}],
      },
      title: '新增',
      addPoliceCriminalInvestigationDialogVisible: false,
      smsSendingSituationDialogVisible: false,
      smsList: [],
      policeCriminalInvestigationMapDialogVisible: false,
      tableData2: [],
      isShowPoliceBut: true,
      AMap: undefined,
      map: undefined,
      polygon: undefined,
      marker: undefined,
      lngLat: undefined,
    }
  },
  computed: {
    tableHeight() {
      let h = document.body.clientHeight - 295;
      return h;
    }
  },
  mounted() {
    let self = this;
    window.addEventListener('resize', () => {
      self.getZoom();
    });
    this.getZoom();
    this.queryList();
  },
  methods: {
    getZoom() {
      let self = this;
      let w = document.body.clientWidth;
      if (w < self.width) {
        self.zoom = (w / self.width) - 0.1;
      } else {
        self.zoom = 1;
      }
      console.log('zoom zoom', this.zoom)
    },
    handlerSendSms(row) {
      let data = {
        phone: row.receiverPhone,
        policeCriminalInvestigationId: row.id
      }
      let self = this;
      sendSms(data).then(res => {
        const {code} = res.data;
        if (200 === code) {
          this.$message({
            message: '短信已发送',
            type: 'success'
          });
          self.queryList();
        } else {
          this.$message({
            message: '短信发送失败',
            type: 'error'
          });
        }
      })
    },
    submitMap() {
      let content;
      let url;
      if (!this.currentFeedbackData.id) {
        content = "刑侦信息\n" +
          "嫌疑人：" + this.currentPSInfo.receiver + "\n" +
          "联系电话：" + this.currentPSInfo.receiverPhone + "\n" +
          "地址：" + this.currentPSInfo.address;
      } else {
        content = "刑侦信息\n" +
          "嫌疑人：" + this.currentPSInfo.receiver + "\n" +
          "联系电话：" + this.currentPSInfo.receiverPhone + "\n" +
          "地址：" + this.currentFeedbackData.mapAddress + "\n";
        url = "https://m.amap.com/share/index/lnglat=" + this.currentFeedbackData.coordinates + "&name=" + encodeURIComponent(this.currentFeedbackData.mapAddress) + "&src=uriapi&callnative=1";
      }
      // let data = {
      //   "id": this.currentPSInfo.id,
      //   "content": content,
      //   "feedbackId": this.currentFeedbackData.id
      // }
      // this.sendMsg(data);
      content += url;
      copyText(content, this);
    },
    // 关闭新增警情弹框
    handleCloseAddPoliceCriminalInvestigationDialog: function () {
      this.addPoliceCriminalInvestigationDialogVisible = false;
    },
    // 打开短信发送情况弹框
    handleOpenSmsSendingSituationDialog: function (row) {
      this.smsList = row.smsList;
      this.smsSendingSituationDialogVisible = true;
    },
    // 关闭短信发送情况弹框
    handleCloseSmsSendingSituationDialog: function () {
      this.smsSendingSituationDialogVisible = false;
    },
    sendMsg(data) {
      sendMsg(data).then(res => {
        const {data, code} = res.data;
        if (code === 200) {
          this.$message({
            message: '出警成功',
            type: 'success'
          });
          self.queryList();
          self.getGeneralView();
          self.handleCloseWecomDialog();
          self.handleClosePoliceInformationMapDialog();
        }
      })
    },
    // 打开警情地图弹框
    handleOpenPoliceCriminalInvestigationMapDialog: function (row) {
      let self = this;
      this.currentPSInfo = row;
      if (row.feedBackList && row.feedBackList.length > 0) {
        this.currentFeedbackData = row.feedBackList[0];
        this.tableData2 = row.feedBackList;
        this.lngLat = this.tableData2[0].coordinates.split(',');
        console.log("tableData2", this.tableData2);
        this.tableData2.forEach(item => {
          item.receiver = row.receiver;
          item.receiverPhone = row.receiverPhone;
          if (item.deptList && item.deptList.length > 0) {
            item.deptId = item.deptList[0].id;
            self.deptChange(item, item.deptId);
          }
        });
        this.policeCriminalInvestigationMapDialogVisible = true;
        if (row.status === 1) {
          this.isShowPoliceBut = false;
        } else {
          this.isShowPoliceBut = true;
        }
        this.initAMap();
        this.$nextTick(() => {
          if (self.$refs.singleTable) {
            self.$refs.singleTable.setCurrentRow(self.tableData2[0]);
          }
        })
      } else {
        this.$confirm('接收人未上传位置信息, 是否继续出警?', '请确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // self.loadWecomTree();
          // self.wecomTreeVisible = true;
          let content = "刑侦信息\n" +
            "嫌疑人：" + this.currentPSInfo.receiver + "\n" +
            "联系电话：" + this.currentPSInfo.receiverPhone + "\n" +
            "地址：" + this.currentPSInfo.address;
          // let data = {
          //   "id": this.currentPSInfo.id,
          //   "content": content,
          //   "feedbackId": this.currentFeedbackData.id
          // }
          // this.sendMsg(data);
          copyText(content, this);
        });
      }
    },
    // 初始化地图
    initAMap() {
      let self = this;
      AMapLoader.load({
        key: "5da1f8bb31f8532695a0fb696d584fae", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Polygon', 'AMap.Marker'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        //加载 AMapUI
        AMapUI: {
          version: "1.1", // AMapUI 版本
        }
      })
        .then((AMap) => {
          self.AMap = AMap;
          self.map = new AMap.Map("map", {
            WebGLParams: {
              preserveDrawingBuffer: true
            },
            // 设置地图容器id
            // viewMode: "3D", // 是否为3D地图模式
            zoom: 14, // 初始化地图级别
            center: [122.766159, 41.517449], // 初始化地图中心点位置，沈阳中心点
          });
          console.log("self.lngLat", self.lngLat, self.lngLat[0], self.lngLat[1]);
          let marker = new self.AMap.Marker({
            position: new self.AMap.LngLat(self.lngLat[0], self.lngLat[1]),
            anchor: 'bottom-center',
          });
          self.map.add(marker);
          self.map.setFitView(marker);
          self.map.setZoom(14);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 关闭警情地图弹框
    handleClosePoliceCriminalInvestigationMapDialog: function () {
      this.currentFeedbackData = {};
      this.currentPSInfo = {};
      this.policeCriminalInvestigationMapDialogVisible = false;
      this.AMap = undefined;
      this.polygon = undefined;
      this.marker = undefined;
      if (this.map) {
        this.map.destroy();
        this.map = undefined;
      }
    },
    handleTable2CurrentChange(row) {
      this.currentFeedbackData = row;
      if (row && row.coordinates && this.map && this.AMap) {
        this.map.clearMap();
        let lngLat = row.coordinates.split(",");
        let self = this;
        this.$nextTick(() => {
          let marker = new self.AMap.Marker({
            position: new self.AMap.LngLat(lngLat[0], lngLat[1]),
            anchor: 'bottom-center',
          });
          self.map.add(marker);
          self.map.setFitView(marker);
          self.map.setZoom(14);
        })
      } else {
        this.lngLat = row.coordinates.split(",");
      }
    },
    deptChange(row, e) {
      let leader = '';
      console.log(row, e);
      row.deptList.forEach(item => {
        if (item.id === e) {
          leader = item.leader;
        }
      })
      this.$set(row, 'leader', leader);
    },
    // 新增警情
    addPoliceCriminalInvestigation: function () {
      this.title = '新增';
      this.addPoliceCriminalInvestigationDialogVisible = true;
      this.addForm = {};
      if (this.$refs['addForm']) {
        this.$refs['addForm'].clearValidate();
        this.$refs['addForm'].resetFields();
      }
    },
    handlerEdit(row) {
      let self = this;
      getDetails(row.id).then(res => {
        const {data, code} = res.data;
        if (code === 200) {
          self.addForm = data;
          if (data && data.category) {
            self.categoryChange(data.category);
          }
          self.title = '编辑';
          self.addPoliceCriminalInvestigationDialogVisible = true;
        }
      })
    },
    submitDialog() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.submit();
        }
      });
    },
    //提交新增/编辑信息
    submit() {
      let self = this;
      this.addForm.status = 0;
      submit(this.addForm).then((res) => {
        const {code} = res.data;
        if (code === 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          self.addForm = {};
          if (self.$refs['addForm']) {
            self.$refs['addForm'].clearValidate();
            self.$refs['addForm'].resetFields();
          }
          self.queryList();
          self.handleCloseAddPoliceCriminalInvestigationDialog();
        }
      });
    },
    handlerDelete(row) {
      let self = this;
      this.$confirm('此操作将永久删除该警情, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCriminalInvestigation(row.id).then(res => {
          const {code} = res.data;
          if (code === 200) {
            self.queryList();
          }
        })
      });
    },
    resetForm() {
      this.pageForm = {
        current: 1,
        size: 20,
        total: 0,
        receiver: '',
        receiverPhone: '',
        searchType: 3
      };
      this.daterange = [];
      this.getList();
    },
    handleSizeChange(val) {
      this.pageForm.current = 1;
      this.pageForm.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageForm.current = val;
      this.getList();
    },
    queryList() {
      this.pageForm.current = 1;
      this.getList();
    },
    // 列表查询
    getList: function () {
      if (this.getListTimeout) {
        clearTimeout(this.getListTimeout);
        this.getListTimeout = undefined;
      }
      let self = this;
      if (this.daterange) {
        this.pageForm.startDate = this.daterange[0];
        this.pageForm.endDate = this.daterange[1];
      } else {
        this.pageForm.startDate = undefined
        this.pageForm.endDate = undefined
      }
      getList(this.pageForm).then(res => {
        const {data, code} = res.data;
        if (code === 200) {
          self.tableData = data.records;
          self.pageForm.total = res.data.data.total;
          self.pageForm.size = res.data.data.size;
        }
      })
      this.getListTimeout = setTimeout(() => {
        self.getList();
      }, 30 * 1000);
    },
  }
}
</script>

<style scoped lang="scss">
.policeCriminalInvestigationList {
  .list-search {
    padding: 0 0 0 25px;
    margin: 20px 0;

    .singe-search {
      width: auto;
      height: auto;
      line-height: 36px;
      margin-top: 5px;

      .el-input {
        width: 200px;
        height: 37px;

        ::v-deep .el-input__inner {
          height: 36px;
          line-height: 36px;
        }
      }

      .el-date-editor {
        width: 230px;
        height: 36px;
      }

      .singe-search-btn1 {
        width: 88px !important;
        height: 36px !important;
        background: #2E488B !important;
        box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
        border-radius: 4px 4px 4px 4px !important;
        opacity: 1 !important;
        padding: 0 !important;

        font-size: 14px !important;
        font-family: PingFang SC-Regular, PingFang SC !important;
        font-weight: 400 !important;
        color: #FFFFFF !important;
      }

      .singe-search-btn2 {
        width: 88px !important;
        height: 36px !important;
        background: #FFFFFF !important;
        box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
        border-radius: 4px 4px 4px 4px !important;
        opacity: 1 !important;
        border: 1px solid #C1D3EE !important;
        padding: 0 !important;

        font-size: 14px !important;
        font-family: PingFang SC-Regular, PingFang SC !important;
        font-weight: 400 !important;
        color: #2E488B !important;
      }
    }
  }

  .table-main {
    margin-left: 25px;
  }
}

::v-deep .policeCriminalInvestigationMapDialog {
  .el-dialog__body {
    max-height: 700px
  }

  .map {
    width: 1115px;
    height: 384px;
    box-shadow: 0px 6px 40px 5px rgba(0, 0, 0, 0.03), 0px 6px 8px 0px rgba(0, 0, 0, 0.05);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
    border: 1px solid rgba(54, 121, 222, 0.5);
  }
}


.scrollable-div {
  width: 90%; /* 设置 div 的宽度 */
  margin: 0 auto;
  height: 550px; /* 设置 div 的高度 */
  overflow: auto; /* 垂直方向上显示滚动条 */
  border: 1px solid #ccc; /* 边框样式 */
  padding: 15px; /* 内边距 */
}

// 不可全选样式
::v-deep .el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display: inline-block;
  }

  .el-checkbox .el-checkbox__inner {
    display: none;
  }
}
</style>
